<template>
  <div>
    <zeda-dialog
      v-model="visible"
      width="500px"
      title="导入"
      :before-close="handleClose"
    >
      <el-form ref="form" :model="model" :rules="rules" label-width="100px">
        <el-form-item label="版本号" prop="versionCode">
          <el-input v-model="model.versionCode" size="small"></el-input>
        </el-form-item>
        <el-form-item label="上传文件" prop="file">
          <FileUpload
            v-model="model.file"
            :fileType="['bin']"
            accept=".bin"
            :file-size="1"
            :limit="1"
            @input="getList"
          ></FileUpload>
        </el-form-item>
      </el-form>

      <form-button
        slot="footer"
        submit-text="提交审核"
        @submit="submitFileForm"
        @cancel="handleClose"
      ></form-button>
    </zeda-dialog>
  </div>
</template>
  <script>
import { upload } from "@/api/iot/upgrade";
import FormButton from "@/components/FormButton";
export default {
  components: {
    FormButton,
  },
  props: {
    visible: { type: Boolean, default: false },
  },
  data() {
    return {
      model: { versionCode: "", file: [] },
      filelist: [],
      rules: {
        versionCode: [
          {
            required: true,
            message: "请输入版本号",
            trigger: "blur",
          },
        ],
        file: [
          {
            required: true,
            message: "请选择文件",
            trigger: ["blur", "change"],
          },
        ],
      },
    };
  },
  methods: {
    getList(data) {
      this.filelist = data;
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const data = {
            fileName: this.filelist[0].name,
            filePath: this.filelist[0].url,
            deviceType: 0,
            versionCode: this.model.versionCode,
          };
          upload(data)
            .then((res) => {
              if (res.code === 700) {
                this.$message.warning(res.msg);
                return false;
              }
              this.$message.success("操作成功");
              this.handleClose(true);
            })
            .catch(() => {
              // this.$message.error("系统错误,请联系管理员!300702");
            });
        }
      });
    },
    handleClose(status) {
      this.$refs["form"].resetFields();
      this.$emit("update:visible", false);
      this.$emit("close", typeof status === "boolean" ? status : false);
    },
  },
};
</script>
